package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.util.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * UserController处理与用户相关的API请求。
 */
@CrossOrigin
@RestController
@RequestMapping("v1")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public List<User> getAllUsers() {
        return userService.findUserAll();
    }

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.findUserID(id);
    }

    @PostMapping("/user")
    public Integer addUser(@RequestBody User user) {
        return userService.insertUser(user);
    }

    @PutMapping("/user")
    public Integer updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @GetMapping("/v1/user/{userId}")
    public Map<String, Object> getUserDetails(@PathVariable Integer userId) {
        return userService.getCompleteUserDetails(userId);
    }

    //myhome中弹窗中的信息修改
    @PutMapping("/update/{id}")
    public Integer updateUserInfo(@PathVariable("id") Integer id, @RequestBody User user) {
        user.setUser_id(id); // 确保User对象中的id被设置为路径变量id
        return userService.updateUserInfo(user);
    }

    //获取用户统计数据（总用户数、活跃用户数、新增用户数、封禁用户数）
    @GetMapping("/stats")
    public Map<String, Integer> getUserStats() {
        return Map.of(
                "totalUsers", userService.getTotalUserCount(),
                "activeUsers", userService.getActiveUserCount(),
                "newUsers", userService.getNewUserCount(),
                "bannedUsers", userService.getBannedUserCount()
        );
    }


    @DeleteMapping("/user/{id}")
    public Integer deleteUser(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }

    @GetMapping("/user/pages")
    public PageInfo<User> getUsersByPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        return userService.findUserByPage(pageNum, pageSize);
    }

    //上传图片
    @PostMapping("/user/upload")
    public String getPicFileName(MultipartFile file) {
        String oldFileName = file.getOriginalFilename();
        System.out.println(oldFileName);
        String typeName = oldFileName.substring(oldFileName.lastIndexOf('.'));

        String filePath = FileUtil.getUploadFilePath();
        System.out.println(typeName);
        String newFileName = System.currentTimeMillis() + typeName;

        try {
            FileUtil.uploadFile(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }


    //判断用户登录用户名和密码正确性
//    @PostMapping("/right")
//    public int login(
//            @RequestParam("user_name") String user_name,
//            @RequestParam("password") String password) {
//        int result = 0;
//        if (userService.login(user_name, password)) {
//            result = 1;
//        }
//        return result;
//    }

    //用户登录
    @PostMapping("/right")
    public ResponseEntity<?> login(@RequestParam("user_name") String user_name,
                                   @RequestParam("password") String password) {
        User user = userService.login(user_name, password);  //获取用户对象 才可以将用户名、用户id传到前端
        if (user != null) {
            return ResponseEntity.ok().body(user); // 返回用户信息
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("账号或密码错误");
        }
    }

    //获取用户信息显示在HisHome上
    @GetMapping("/Userinfo/{user_id}")
    public User getUserinfo(@PathVariable Integer user_id) {
        return userService.getUserinfo(user_id); // 返回用户信息
    }

    //注册页新增用户
    @PostMapping("/userRegister")
    public ResponseEntity<?> registerUser(@RequestBody User user) {
        try {
            Integer result = userService.insertUserRegister(user);
            if (result > 0) {
                return ResponseEntity.ok("success");
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名已存在");
            }
        } catch (DuplicateKeyException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名已存在");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("error");
        }

    }


    //注册页修改密码
    @PostMapping("/change-password")
    public ResponseEntity<?> changePassword(@RequestParam("user_name") String user_name,
                                            @RequestParam("old_password") String old_password,
                                            @RequestParam("new_password") String new_password) {
        try {
            User user = userService.login(user_name, old_password);
            if (user != null) {
                Integer result = userService.updatePassword(user_name, new_password);
                if (result > 0) {
                    return ResponseEntity.ok("密码修改成功");
                } else {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("密码修改失败");
                }
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("旧密码错误");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器错误");
        }
    }
}